package com.mall.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.ui.ModelMap;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.mall.common.attributes.CommonAttributes;

/**
 * 拦截器，拦截不登录用户操作
 * @author tgy
 *
 */
public class UsersInterceptor extends HandlerInterceptorAdapter{

	Logger logger = Logger.getLogger(UsersInterceptor.class);
	private String loginUrl = "/view/login.html";
	
	//URL编码字符类型  项目名.properties 配置文件设置
	@Value("${default_encoding}")
	private String charset;
	
	@Override
	public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {
		HttpSession session = request.getSession();
		ModelMap user = (ModelMap) session.getAttribute(CommonAttributes.SESSION_ATTRIBUTE_NAME);
		if(user != null) {
			logger.info("################当前登录用户账号："+user.get("account"));
			return true;
		}
		String xrw = request.getHeader("X-Requested-With");
		if(xrw != null && xrw.equalsIgnoreCase("XMLHttpRequest")) {//AJAX请求处理
			response.addHeader("loginStatus", "accessDenied");//拒绝访问，请登录
			response.sendError(403);
			return false;
		}
		logger.info("####################登录地址："+loginUrl);
		response.sendRedirect(request.getContextPath() + loginUrl);
		return false;
	}
	
//	@Override
//	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//		if(modelAndView != null) {
//			String viewName = modelAndView.getViewName();
//			if(!viewName.startsWith("redirect:")) {
//				modelAndView.addObject("member", null);
//			}
//		}
//	}

	public String getLoginUrl() {
		return loginUrl;
	}

	public void setLoginUrl(String loginUrl) {
		this.loginUrl = loginUrl;
	}
}
